package com.comp6521.project01;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class InputBuffer extends Buffer {

	private BufferedReader bufferReader = null;
	
	public InputBuffer(int bufferSize, String filename) {
		super(bufferSize, filename);
		try {
			bufferReader = new BufferedReader(new FileReader(getFilename()));
			load();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	// load from file
	boolean load() {
		String line = null;
		try {
			while ((data.size() <= getBufferSize()) && (line = bufferReader.readLine()) != null)
				data.add(Integer.parseInt(line));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (line != null)
			return true;
		else
			return false;
	}
	
	// pop and remove the top
	public Integer popTop() {
		
		boolean res = true;
		if (data.isEmpty())
			res = load();
		
		if (res)
			return data.poll();
		else
			return null;
	}
	
	// Retrieve top but don't remove it
	public Integer getFirst() {
		
		boolean res = true;
		if (data.isEmpty())
			res = load();
		
		if (res)
			return data.element();
		else
			return null;
	}
	
	void close() {
		try {
			bufferReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
